package cn.lili.trigger.interfaces.impl;

import cn.hutool.json.JSONUtil;
import cn.lili.cache.Cache;
import cn.lili.common.utils.DateUtil;
import cn.lili.trigger.delay.queue.PromotionDelayQueue;
import cn.lili.trigger.enums.DelayStatusEnums;
import cn.lili.trigger.interfaces.TimeTrigger;
import cn.lili.trigger.model.TimeTriggerMsg;
import cn.lili.trigger.util.DelayQueueTools;
import cn.lili.util.AmqpMessage;
import cn.lili.util.AmqpSender;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.messaging.Message;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Component;

/**
 * 延时任务实现
 *
 * @author paulG
 * @since 2020/11/5
 **/
@Component
@Slf4j
@RequiredArgsConstructor
public class RabbitmqTimerTrigger implements TimeTrigger {
    private final AmqpSender amqpSender;
    private final Cache<String> cache;
    private final PromotionDelayQueue promotionDelayQueue;


    @Override
    public void addDelay(TimeTriggerMsg timeTriggerMsg) {
        //执行器唯一key
        String uniqueKey = timeTriggerMsg.getUniqueKey();
        //执行任务key 任务实际执行时会根据规则重新生成字符串，然后判定是否标识需要执行
        String generateKey = DelayQueueTools.generateKey(timeTriggerMsg.getTriggerExecutor(), timeTriggerMsg.getTriggerTime(), uniqueKey);
        //执行标识写在缓存中
        this.cache.put(generateKey, DelayStatusEnums.RUN.name());
        //设置延时任务
        if (Boolean.TRUE.equals(promotionDelayQueue.addJob(JSONUtil.toJsonStr(timeTriggerMsg), timeTriggerMsg.getTriggerTime()))) {
            log.info("延时任务标识： {}", generateKey);
            log.info("定时执行在【" + DateUtil.toString(timeTriggerMsg.getTriggerTime(), "yyyy-MM-dd HH:mm:ss") + "】，消费【" + timeTriggerMsg.getParam().toString() + "】");
        } else {
            log.error("延时任务添加失败:{}", timeTriggerMsg);
        }
    }

    @Override
    public void execute(TimeTriggerMsg timeTriggerMsg) {
        this.addExecute(timeTriggerMsg);
    }


    @Override
    public void edit(TimeTriggerMsg oldTimeTriggerMsg, TimeTriggerMsg timeTriggerMsg) {
        this.delete(oldTimeTriggerMsg);
        this.addDelay(timeTriggerMsg);
    }

    @Override
    public void delete(TimeTriggerMsg timeTriggerMsg) {
        String generateKey = DelayQueueTools.generateKey(timeTriggerMsg.getTriggerExecutor(), timeTriggerMsg.getTriggerTime(), timeTriggerMsg.getUniqueKey());
        log.info("删除延时任务{}", generateKey);
        this.cache.put(generateKey, DelayStatusEnums.STOP.name());
    }


    /**
     * 将任务添加到mq，mq异步队列执行。
     * <p>
     * 本系统中redis相当于延时任务吊起机制，而mq才是实际的业务消费，执行任务的存在
     *
     * @param timeTriggerMsg 延时任务消息
     */
    private void addExecute(TimeTriggerMsg timeTriggerMsg) {

        Message<TimeTriggerMsg> message = MessageBuilder.withPayload(timeTriggerMsg).build();
        log.info("延时任务发送信息：{}", message);

        AmqpMessage amqpMessage = AmqpMessage.builder()
                .message(timeTriggerMsg)
                .exchange(timeTriggerMsg.getExchange())
                .routingKey(timeTriggerMsg.getRoutingKey())
                .build();

        this.amqpSender.send(amqpMessage);
    }

}
